package com.itheima.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import com.itheima.utils.DaoInstanceFactory;

import java.util.List;

public class ServiceIml implements UserService {

    public List<User> findAll() {
        /*try {
            //获取核心配置文件
            InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
            //获取工厂
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
            //得到SqlSession对象
            SqlSession sqlSession = factory.openSession();
            //获取dao代理对象
            UserDao dao = sqlSession.getMapper(UserDao.class);
            //调用dao方法查询
            List<User> users = dao.findAll(queryUser);
            //释放资源
            sqlSession.close();
            return users;

        } catch (IOException e) {
            e.printStackTrace();
        }*/
        return null;
    }

    public User login(User user) {

        UserDao dao = DaoInstanceFactory.getMapper(UserDao.class);

        //调用dao方法查询
        User user1 = dao.login(user);

        return user1;


    }

    public void addUser(User user) {


        UserDao dao = DaoInstanceFactory.getMapper(UserDao.class);
        //调用dao方法查询
        dao.addUser(user);


    }

    public void deleteUser(String id) {


        UserDao dao = DaoInstanceFactory.getMapper(UserDao.class);

        //调用dao方法查询
        dao.deleteUser(id);


    }

    public User findUserById(String id) {


        UserDao dao = DaoInstanceFactory.getMapper(UserDao.class);
        //调用dao方法查询
        User user = dao.findUserById(id);

        return user;


    }

    public void updateUser(User user) {


        UserDao dao = DaoInstanceFactory.getMapper(UserDao.class);
        //调用dao方法查询
        dao.updateUser(user);


    }

    public void delSelectedUser(String[] ids) {

        UserDao dao = DaoInstanceFactory.getMapper(UserDao.class);

        //调用dao方法查询
        if (ids != null) {
            dao.delSelectedUser(ids);
        }


    }

    public PageInfo<User> pageQuery(String currentPageStr, String pageSizeStr, User queryUser) {


        UserDao dao = DaoInstanceFactory.getMapper(UserDao.class);

        int currentPage = 1;
        try {
            currentPage = Integer.parseInt(currentPageStr);
        } catch (NumberFormatException e) {

        }
        int pageSize = 5;
        try {
            pageSize = Integer.parseInt(pageSizeStr);
        } catch (NumberFormatException e) {
        }


        //设置分页参数
        PageHelper.startPage(currentPage, pageSize);

        // 调用dao查询
        List<User> users = dao.findAll(queryUser);

        // 封装到分页信息对象中
        PageInfo<User> pageInfo = new PageInfo(users);
        return pageInfo;

    }


}
